package com.example.footballsystem.service;

import com.example.footballsystem.entity.Book;
import com.example.footballsystem.mapper.BookMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class BookService {
    @Autowired
    BookMapper bookMapper;

    //获取全部预定信息
    public List<Book> getAllBook(){
        return bookMapper.getAllBook();
    }
    public List<Book> searchBook(String info){
        List<Book> resultList = new ArrayList<>();
        int count = 0;

        try{
            if(!bookMapper.getBookByField(Integer.parseInt(info)).isEmpty()){
                resultList.addAll((bookMapper.getBookByField(Integer.parseInt(info))));
                count++;
            }
            if(!bookMapper.getBookByID(Integer.parseInt(info)).isEmpty()){
                resultList.addAll((bookMapper.getBookByID(Integer.parseInt(info))));
                count++;
            }
        }catch (NumberFormatException e){
            if(!bookMapper.getBookByUserAccount(info).isEmpty()) {
                resultList.addAll((bookMapper.getBookByUserAccount(info)));
                count++;
            }
            for (int i=0;i<count;i++) {
                for (int j=i+1;j<count;j++) {
                    if(Objects.equals(resultList.get(j).getBookID(), resultList.get(j).getBookID())){
                        log.info(i+" "+j);
                        resultList.remove(j);
                        j--;
                        count--;
                    }
                }
            }
            return resultList;
        }
        if(!bookMapper.getBookByUserAccount(info).isEmpty()) {
            resultList.addAll((bookMapper.getBookByUserAccount(info)));
            count++;
        }
        for (int i=0;i<count;i++) {
            for (int j=i+1;j<count;j++) {
                if(Objects.equals(resultList.get(j).getBookID(), resultList.get(j).getBookID())){
                    log.info(i+" "+j);
                    resultList.remove(j);
                    j--;
                    count--;
                }
            }
        }
        //log.info(resultList.toString());
        return resultList;
    }
    //增加预约
    public Boolean addBook(Book book){
        Timestamp time = new Timestamp(System.currentTimeMillis());
        book.setCreateDate(time.toString());
        return bookMapper.addBook(book);
    }
    //删除预约
    public Boolean deleteBook(Book book){
        return bookMapper.deleteBook(book.getBookID());
    }
}
